import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class UploadDBConfigToZK {

    public static void main(String[] args) {
        InputStream resourceAsStream =
                UploadDBConfigToZK.class.getClassLoader()
                        .getResourceAsStream("application.properties");

        Properties properties = new Properties();
        CuratorFramework client = null;
        try {
            properties.load(resourceAsStream);

            /*
            datasource.config.zkpath=/zdy_db/hikaricp
datasource.config.zkUrl=localhost:2181,localhost:2182,localhost:2183
             */

            String zkPath = properties.getProperty("datasource.config.zkpath");
            String zkUrl = properties.getProperty("datasource.config.zkUrl");

            int sessionTimeoutMs = 50000;
            int connectionTimeoutMs = 50000;
            RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);

            client = CuratorFrameworkFactory
                    .builder().connectString(zkUrl)
                    .sessionTimeoutMs(sessionTimeoutMs)
                    .connectionTimeoutMs(connectionTimeoutMs)
                    .retryPolicy(retryPolicy).build();

            client.start();
            Stat stat1 = client.checkExists().forPath(zkPath);
            if(stat1 == null) {
                String createPath = client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(zkPath);
                System.out.println(createPath);
            }
            /*
            {"jdbc.driver":"org.postgresql.Driver","jdbc.url":"jdbc:postgresql://localhost:5432/test","jdbc.username":"postgres","jdbc.password":"wuhuahe91926317"}
             */
            String dsConfig =
                    "{\"jdbc.driver\":\"org.postgresql.Driver\",\"jdbc.url\":\"jdbc:postgresql://localhost:5432/test\",\"jdbc.username\":\"postgres\",\"jdbc.password\":\"wuhuahe91926317\"}";
            Stat stat = client.setData().forPath(zkPath, dsConfig.getBytes("GBK"));
            System.out.println(stat);

            Thread.sleep(1000);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(client != null){
                client.close();
            }
        }
    }
}
